﻿using CommonLib;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Channels;
using System.Threading.Tasks;

namespace ConsoleAppConsumer2;

internal class TestPrefetch
{
    private static readonly string queueName = "test_prefetch";

    public static void Test()
    {
        Console.WriteLine("Consumer2 收到了消息 时间较短");
        // 1 创建信道 channel
        var channel = RabbitMQUtil.CreateChannel();

        // 2 设置预设值5 这个方法第一个参数只能设置为0 第二个参数代表预取值，值越大代表一次先取到的消息越多，一般设置300-400 即可，需要根据配置设置
        channel.BasicQos(0, 5, false);

        // 3 声明回调方法
        var consumer = new AsyncEventingBasicConsumer(channel);
        consumer.Received += Consumer_Received;
        async Task Consumer_Received(object sender, BasicDeliverEventArgs @event)
        {
            //Console.WriteLine(sender);
            //var channel = sender as IModel;
            try
            {
                var body = @event.Body.ToArray();
                var msg = Encoding.UTF8.GetString(body);
                Console.WriteLine("Consumer2 收到了消息" + msg);
                channel?.BasicAck(@event.DeliveryTag, false);
                await Task.Delay(1000);
            }
            catch (Exception ex)
            {
                channel?.BasicReject(@event.DeliveryTag, true);
                Console.WriteLine("处理消息：" + ex.Message);
            }
        }

        // 4 消费消息
        channel.BasicConsume(queue: queueName, autoAck: false, consumer: consumer);
        Console.ReadLine();
    }

}
